﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Telerik.Windows.Controls;
using DunSilverlight.Comm;
using DunLibrary.Dun;

namespace DunSilverlight.Views
{
    public partial class ThirdApproval : Page
    {
        private IList<DunLibrary.Organization.Organization> orgs;

        private DunLibrary.User.User user = AppGlobal.CurrentUser;

        private DunLibrary.Query.QueryCondition queryCondition;

        private const int Paging_Max_Result = 19;

        public ThirdApproval()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(ThirdApproval_Loaded);

        }

        void ThirdApproval_Loaded(object sender, RoutedEventArgs e)
        {
            Tools.ShowMask(true);
            Action<IList<DunLibrary.Organization.Organization>> getOrgCallBack = (IList<DunLibrary.Organization.Organization> orgs) =>
                {
                    this.orgs = orgs;
                    cmbOrg.ItemsSource = orgs;
                    Tools.ShowMask(false);
                    SetRightControl();
                };
            AppGlobal.GetOrganizations(getOrgCallBack);

            cmbPeriod.ItemsSource = AppGlobal.Periods;

            cmbCheck.ItemsSource = new List<CheckState>{ new CheckState { Name = "审核", State = true }, new CheckState { Name = "未审核", State = false } };

            cmbCheckWorkType.ItemsSource = new List<CheckWorkType> { new CheckWorkType { Name = "本人审核", WorkType = 1 }, new CheckWorkType { Name = "本人提交", WorkType = 2 },new CheckWorkType{Name="所有人",WorkType=3} };

        }
        /// <summary>
        /// 根据登陆用户设置权限
        /// </summary>
        private void SetRightControl()
        {
            try
            {
                if (user.Organization.Parent == null)//总部
                {
                    cmbOrg.IsEnabled = true;
                }
                else
                {
                    DunLibrary.Organization.Organization org = orgs.FirstOrDefault(p => p.Id == user.Organization.Id);
                    cmbOrg.SelectedItem = org;
                    cmbOrg.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessage(ex.Message, "", false);
            }
        }

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheck_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckVerify())
                return;

            BatchCheck(true);
        }
        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUnCheck_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckVerify())
                return;

            BatchCheck(false);
        }
        /// <summary>
        /// 批量提交
        /// </summary>
        /// <param name="check"></param>
        private void BatchCheck(bool check)
        {
            try
            {
                
                IList<int> selIds = dgdInv.SelectedItems.Select(p =>(p as InvestigateRequest).Id).ToList<int>();

                InvRequestService.InvestigateRequestServiceClient ser = new InvRequestService.InvestigateRequestServiceClient();

                ser.BatchCheckCompleted += (object sender1, InvRequestService.BatchCheckCompletedEventArgs e1) =>
                    {
                        QueryPaging(queryCondition);
                        ser.CloseAsync();
                    };

                string strIds = Newtonsoft.Json.JsonConvert.SerializeObject(selIds);

                ser.BatchCheckAsync(strIds, user.Id, check);
            }
            catch (Exception ex)
            {
                Tools.ShowMessage(ex.Message, "", false);
            }

        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            if (!QueryVerify())
                return;

            BuildHql();
            QueryPaging(queryCondition);
        }

        /// <summary>
        /// 验证有效性
        /// </summary>
        private bool QueryVerify()
        {
            if (cmbCheckWorkType.SelectedItem == null)
            {
                Tools.ShowMessage("请选择查询类别", "", false);
                return false;
            }

            //假如没有查看所有单据的权限
            if (!RightManagement.VerifyRight(RightManagement.Right_View_All_Case) )
            {
                if ((cmbCheckWorkType.SelectedItem as CheckWorkType).WorkType == 3)
                {
                    Tools.ShowMessage("你没有查询所有催收信息的权限", "", false);
                    return false;
                }
            }

            return true;
        }
        /// <summary>
        /// 审核前检查
        /// </summary>
        /// <returns></returns>
        private bool CheckVerify()
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Investigate_Check))
            {
                Tools.ShowMessage("你没有审核权限!","",false);
                return false;
            }

            CheckWorkType cwt=cmbCheckWorkType.SelectedItem as CheckWorkType;

            if (cwt == null || cwt.WorkType != 1)
            {
                Tools.ShowMessage("查询类别请选择[本人审核]", "", false);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 建立hql查询条件
        /// </summary>
        private void BuildHql()
        {
            string hqlwhere = "where inv.Case.Catalog.IsFinish=false ";//必须是还没有结案的！owen 2011-12-17

            int workType = (cmbCheckWorkType.SelectedItem as CheckWorkType).WorkType;

            switch (workType)
            {
                case 1:
                    hqlwhere += "and inv.Checker.Id=" + user.Id;
                    break;
                case 2:
                    hqlwhere += "and inv.Case.Oper.Id=" + user.Id;
                    break;
                case 3:
                    hqlwhere += "";//没有限制条件
                    break;

            }

            if (!string.IsNullOrEmpty(txtYear.Text.Trim()))
            {
                hqlwhere += " and inv.Case.Year=" + txtYear.Text.Trim();
            }

            if (cmbPeriod.SelectedItem != null)
            {
                hqlwhere += " and inv.Case.Period=" + cmbPeriod.SelectedItem.ToString();
            }

            if (cmbOrg.SelectedItem != null)
            {
                hqlwhere += " and inv.Case.BranchCompany.Id=" + (cmbOrg.SelectedItem as DunLibrary.Organization.Organization).Id;
            }

            if (cmbCheck.SelectedItem != null)
            {
                hqlwhere += " and inv.IsAllow=" + (cmbCheck.SelectedItem as CheckState).State;
            }

            queryCondition = new DunLibrary.Query.QueryCondition();

            queryCondition.HQL = "from InvestigateRequest as inv " + hqlwhere;
            queryCondition.TotalHQL ="select count(*) from InvestigateRequest as inv " + hqlwhere;

            queryCondition.MaxResults = Paging_Max_Result;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="qc"></param>
        private void QueryPaging(DunLibrary.Query.QueryCondition qc)
        {
            if (qc == null || string.IsNullOrEmpty(qc.HQL))
                return;

            InvRequestService.InvestigateRequestServiceClient ser = new InvRequestService.InvestigateRequestServiceClient();
            Tools.ShowMask(true);
            ser.GetListByHQLWithPagingCompleted += (object sender, InvRequestService.GetListByHQLWithPagingCompletedEventArgs e) =>
                {
                    Tools.ShowMask(false);
                    try
                    {
                        int totalCount = 0;

                        IList<InvestigateRequest> invReqs = JsonSerializerHelper.JsonToEntities<InvestigateRequest>(e.Result, out totalCount);

                        rdpInv.NumericButtonCount = totalCount / Paging_Max_Result;//分页好像不对

                        dgdInv.ItemsSource = invReqs;
                    }
                    catch (Exception ex)
                    {
                        Tools.ShowMessage(ex.Message, "", false);
                    }
                    finally
                    {
                        ser.CloseAsync();
                    }
                };
          
            string json =Newtonsoft.Json.JsonConvert.SerializeObject(qc);

            ser.GetListByHQLWithPagingAsync(json);
        }

        private void rdpInv_PageIndexChanged(object sender, PageIndexChangedEventArgs e)
        {

        }

        private void btnView_Click(object sender, RoutedEventArgs e)
        {
            ViewInv();
        }

        /// <summary>
        /// 显示申请的详细信息
        /// </summary>
        private void ViewInv()
        {
            InvestigateRequest inv = dgdInv.SelectedItem as InvestigateRequest;
      
            if (inv != null)
            {
                ThridInvForm frm = new ThridInvForm(inv);

                Tools.OpenWindow("查看第三方调查申请", frm, null);
            }
        }

    }
}
